package cn.edu.sgu.www.mhxysy.service.waiguan.impl;

import cn.edu.sgu.www.mhxysy.dto.waiguan.ColorDTO;
import cn.edu.sgu.www.mhxysy.entity.waiguan.Color;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.mapper.waiguan.ColorMapper;
import cn.edu.sgu.www.mhxysy.redis.repository.impl.ColorRepository;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import cn.edu.sgu.www.mhxysy.service.waiguan.ColorService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class ColorServiceImpl implements ColorService {

    private final ColorMapper colorMapper;
    private final ColorRepository colorRepository;

    @Autowired
    public ColorServiceImpl(ColorMapper colorMapper, ColorRepository colorRepository) {
        this.colorMapper = colorMapper;
        this.colorRepository = colorRepository;
    }

    @Override
    public void insert(ColorDTO colorDTO) {
        Color color = toEntity(colorDTO);

        color.setId(null);

        int insert = colorMapper.insert(color);

        if (insert == 1) {
            colorRepository.deleteList();
        }
    }

    @Override
    public List<Color> selectAll() {
        return colorRepository.selectList();
    }

    @Override
    public Color selectById(Integer id) {
        return colorRepository.selectById(id.toString());
    }

    private Color toEntity(ColorDTO colorDTO) {
        Integer id = colorDTO.getId();
        String name = colorDTO.getName();

        // 验证名称重复
        QueryWrapper<Color> queryWrapper = new QueryWrapper<>();

        queryWrapper.ne(id != null, "id", id);
        queryWrapper.eq("name", name);

        Long count = colorMapper.selectCount(queryWrapper);

        if (count > 0) {
            throw new GlobalException(ResponseCode.CONFLICT, "颜色名称重复！");
        }

        Color color = new Color();

        color.setId(id);
        color.setName(name);

        return color;
    }

}